package cn.sang.service.imp;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Service;

import cn.sang.dao.StudentDao;
import cn.sang.model.Student;
import cn.sang.model.vo.MyListComplsitionVo;
import cn.sang.service.StudentService;
import cn.sang.util.AjaxResult;
import cn.sang.util.StrUtils;

@Service
public class StudentServiceImp implements StudentService{
	
	@Resource
	private StudentDao studentDao;
	
	//我的信息页面   查询当前登录用户所有的作文列表
	public List<MyListComplsitionVo> myListComplsition(HttpServletRequest request) {
		
		HttpSession session = request.getSession();
		
		//获取当前登录用户的 id
		Object attribute = session.getAttribute("sId");
		
		Integer studentId = null;
		if(attribute != null){
			studentId = (int) attribute;
		}
		
		List<MyListComplsitionVo> myListComplsition = studentDao.myListComplsition(studentId);
		
		return myListComplsition;
	}

	//获取学生信息
	public Student getStudentInfo(HttpServletRequest request) {
		HttpSession session = request.getSession();
		
		Object studentId_obj = session.getAttribute("sId");
		
		Integer studentId = null;
		if(studentId_obj!= null){
			studentId = (Integer) studentId_obj;
		}
		
		Student student = studentDao.getStudentInfo(studentId);
		
		return student;
	}

	//学生登陆
	public AjaxResult studentLogin(HttpServletRequest request) {
		HttpSession session = request.getSession();
		
		AjaxResult ajaxResult = new AjaxResult();
		
		String sUserName = request.getParameter("sUserName");
		String sPassWord = request.getParameter("sPassWord");
		
		Map<String, Object> hashMap = new HashMap<String, Object>();
		
		hashMap.put("sUserName", sUserName);
		hashMap.put("sPassWord", sPassWord);
		
		Student student = studentDao.studentLogin(hashMap);
		
		
		if(student == null){
			return AjaxResult.errorResult("用户名密码错误");
		}else{
			session.setAttribute("sId", student.getS_id());
			
			ajaxResult.put("student", student);
			ajaxResult.put("success", true);
			ajaxResult.put("msg", "登陆成功");
			return ajaxResult;
		}
		
	}

	//学生注册
	public AjaxResult studentRegister(HttpServletRequest request) {
		
		String sUserName = request.getParameter("sUserName");
		String sPassWord = request.getParameter("sPassWord");
		
		if(StrUtils.isEmpty(sUserName) || StrUtils.isEmpty(sPassWord)){
			return AjaxResult.errorResult("用户名或密码不能为空");
		}
		
		//查询账户名是否已经被注册
		Student isExistence = studentDao.findByUserName(sUserName);
		if(isExistence != null){
			return AjaxResult.errorResult("用户名已经被注册");
		}
		
		
		Student student = new Student();
		student.setUserName(sUserName);
		student.setPassWord(sPassWord);
		
		try {
			studentDao.studentRegister(student);
			return AjaxResult.successResult("注册成功");
		} catch (Exception e) {
			e.printStackTrace();
			return  AjaxResult.errorResult("注册失败");
		}
		
	}
	
}
